import React, { useCallback } from 'react';
// 导入导航条组件
import Mynavbar from '@/components/Mynavbar';
import {
    Avatar,
    List,
    Space,
    Ellipsis,
    Stepper,
    Checkbox,
    Empty,
    Button,
    SwipeAction,
    Dialog
} from 'antd-mobile';
// import { Action, SwipeActionRef } from 'antd-mobile/es/components/swipe-action'
import { useState, useEffect, useMemo } from 'react';
import { useHistory } from 'react-router-dom'
// 引入购物车接口
import {
    getCarlistApi,
    updatenumApi,
    updateSelectedApi,
    updateSelectedAllApi,
    removeOneCartApi
} from '@/api/car';
import { useSelector } from 'react-redux'
import styled from 'styled-components'
const Mybar = styled.div`
    position: fixed;
    left:0;
    bottom:0;
    display: flex;
    justify-content: space-around;
    height: 50px;
    width: 100%;
    align-items: center;
    background-color: #fff;
`
const Car = () => {
    const his = useHistory();
    const { userId } = useSelector(state => state)
    // console.log('userId', userId);
    // 定义购物车列表数据
    const [carlist, setCarList] = useState([]);

    // 定义请求购物车数据方法
    const getcarlistFn = useCallback(() => {
        //console.log('callback该函数被定义创建一次,但是调用执行多次');
        getCarlistApi({
            userid: userId
        }).then(res => {
            // console.log('res', res);
            if (res.data.code == '10020') {
                setCarList([])
                setCheckedAll(false)
            } else {
                setCarList(res.data.data)
                // 根据返回的数据判断当前的商品是否是全选
                let flag = res.data.data.every(item => item.flag)
                setCheckedAll(flag)
            }
        })
    }, [])

    useEffect(() => {
        // 初始化请求购物车数据列表
        getcarlistFn()
    }, []);

    // 使用useMemo
    // 语法: const 计算属性值 = useMemo(()=>{return 返回值},[依赖的数据])
    const isshowEmpty = useMemo(() => carlist.length > 0 ? false : true, [carlist])

    // 计算总价
    // const 总价 = useMemo(()=>{return 返回值},[carlist]);
    // const sum总和 = arr.reduce((sum,item)=>{return sum+=item},sum的初始值)
    const totalPrice = useMemo(() => {
        // const sumtotal = carlist.reduce((sum, item) => {
        //     return item.flag ? sum += item.originprice * item.num : sum
        // }, 0)
        // return sumtotal  //该返回值就是计算属性的值

        //将上面代码简写:
        return carlist.reduce((sum, item) => item.flag ? sum += item.originprice * item.num : sum, 0)
    }, [carlist])

    // 定义全选状态
    const [checkedAll, setCheckedAll] = useState(false)
    return (
        <div className='car'>
            <Mynavbar isshow={false}>购物车{ }</Mynavbar>
            {/* 购物车主体部分 */}
            {
                isshowEmpty ? <Empty
                    style={{ padding: '64px 0' }}
                    imageStyle={{ width: 128 }}
                    description={
                        <div>
                            <p style={{
                                textAlign: 'center',
                                marginBottom: "20px"
                            }}>暂无数据</p>
                            <Button color='danger' onClick={() => {
                                his.push('/home')
                            }} >立即购物</Button>
                        </div>
                    }
                /> : <List>
                    {
                        carlist.map(item =>
                            <SwipeAction
                                key={item.proid}
                                closeOnAction={true}
                                closeOnTouchOutside={true}
                                rightActions={[
                                    {
                                        key: 'delete',
                                        text: '删除',
                                        color: 'danger',
                                        onClick: async () => {
                                            await Dialog.confirm({
                                                content: '确定要删除吗？',
                                                onConfirm() {
                                                    removeOneCartApi({
                                                        cartid: item.cartid
                                                    }).then(res => {
                                                        console.log('res', res)
                                                        // 重新调用请求购物车列表的数据
                                                        getcarlistFn()
                                                    })
                                                }
                                            })

                                        },
                                    },
                                ]}
                            >
                                <List.Item
                                    prefix={
                                        <div style={{
                                            display: 'flex',
                                            alignItems: 'center'
                                        }}>
                                            <div style={{ marginRight: '10px' }} onClick={e => e.stopPropagation()}>
                                                <Checkbox checked={item.flag} onChange={
                                                    (bool) => {
                                                        // console.log('bool', bool)
                                                        updateSelectedApi({
                                                            cartid: item.cartid,
                                                            flag: bool
                                                        }).then(res => {
                                                            // console.log('res', res)
                                                            // 重新调用请求购物车列表的数据
                                                            getcarlistFn()
                                                        })
                                                    }
                                                } />
                                            </div>
                                            <Avatar src={item.img1} />
                                        </div>

                                    }
                                    description={
                                        <div style={{
                                            display: 'flex',
                                            justifyContent: 'space-between',
                                            alignItems: 'center'
                                        }}>
                                            <span style={{
                                                color: 'red',
                                            }}>${item.originprice.toFixed(2)}元</span>
                                            <Stepper
                                                value={item.num}
                                                min={0}
                                                onChange={value => {
                                                    console.log(value)
                                                    if (value == 0) {
                                                        removeOneCartApi({
                                                            cartid: item.cartid
                                                        }).then(res => {
                                                            console.log('res', res)
                                                            // 重新调用请求购物车列表的数据
                                                            getcarlistFn()
                                                        })

                                                    } else {
                                                        // console.log('value', value)
                                                        // 调用接口修改数量
                                                        // console.log('item', item)
                                                        updatenumApi({
                                                            cartid: item.cartid,
                                                            num: value
                                                        }).then(res => {
                                                            //console.log('res', res)
                                                            // 重新调用请求购物车列表的数据
                                                            getcarlistFn()
                                                        })
                                                    }
                                                }}

                                            />
                                        </div>
                                    }
                                >
                                    <Ellipsis direction='end' style={{ fontSize: '15px' }} content={item.proname} />
                                </List.Item>
                            </SwipeAction>
                        )
                    }

                </List>
            }

            {/* 底部非tabbar */}
            <Mybar>
                <div>
                    <Checkbox checked={checkedAll} onChange={(bool) => {
                        updateSelectedAllApi({
                            userid: userId,
                            type: bool
                        }).then(res => {
                            // console.log('res', res)
                            // 重新调用请求购物车列表的数据
                            getcarlistFn()
                        })
                    }} />全选
                </div>
                <p>
                    合计: {totalPrice.toFixed(2)}元
                </p>
                <Button color='danger'>合计</Button>
            </Mybar>
        </div>
    );
}

export default Car;
